package org.buptsse.listview;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.buptsse.entity.Circle;
import org.buptsse.entity.User;
import org.buptsse.ui.CloudLearningApp;
import org.buptsse.ui.LogoActivity;
import org.buptsse.ui.MainStudyActivity;
import org.buptsse.ui.PostReplyActivity;
import org.buptsse.ui.R;

//import org.buptsse.ui.TreeActivity;
import org.buptsse.utils.ActionUtils;
import org.buptsse.utils.GloableInstance;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MyCirleListPage extends LinearLayout implements OnScrollListener {
	//CloudLearningApp app=(CloudLearningApp)getApplication();
	//String myName=app.getUsername();
	User user=GloableInstance.user;
	String myName=user.getName();
	
	int cid=1;
	SimpleAdapter Adapter;
    ArrayList<HashMap<String, String>> discusslist =new ArrayList<HashMap<String,String>>();
    private final int finish = 0;
	
	private final static int OK = 1;
	private final String URL_CIRCLELIST="fetchJoinCircle.do";//——确定调用函数
	ListView list;//——信件一个list
	int scrollState;
	int count = 40;
	int lastItem;
	int visibleItemCount;
	//Button footerButton;
	//LinearLayout footerProgressBarLayout;// 加载进度滚动条
	ListAdapter listAdapter = new ListAdapter();
	//View viewfoot;
	//private User user=null;//——一个用户
	private int uid;
	private List<Circle> circleList = new ArrayList<Circle>();//——新建一个叫circle类型的数组
	private Context context;
	private ListView listView = null;//——一个界面显示
	//——这个是函数
	Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MyCirleListPage.OK:
				if (null != discusslist) {
					listAdapter.count = discusslist.size();
				} else {
					listAdapter.count = 0;
				}
				listAdapter.notifyDataSetChanged();
				break;
			}
			super.handleMessage(msg);
		}
	};

	public MyCirleListPage(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public MyCirleListPage(Context context, User user) {
		super(context);
		this.user = user;
		this.context = context;
		//uid=user.getId();
		uid=124;
		init();
	}

	private void init() {
		setBackgroundColor(Color.WHITE);
		listAdapter.count=0;
		listView = new ListView(getContext());
		listView.setDivider(new ColorDrawable(Color.WHITE));
		listView.setDividerHeight(1);
		listView.setVerticalFadingEdgeEnabled(false);
		listView.setAdapter(listAdapter);
		listView.setOnScrollListener(this);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				/*
				Circle onSelect = circleList.get(arg2);
				Intent it = new Intent(context,LogoActivity.class);
				it.putExtra("user", user);
				it.putExtra("onSelect", onSelect);
				*/
				HashMap map = discusslist.get(position);
				String username = (String) map.get("username");
				String postid=(String)map.get("postid");
				String time=(String)map.get("time");
				String replynum=(String)map.get("replynum");
				String title=(String)map.get("title");
				String content=(String)map.get("content");
				Intent intent=new Intent(context,PostReplyActivity.class);
				intent.putExtra("postid",postid);
				intent.putExtra("username",username);
				intent.putExtra("time",time);
				intent.putExtra("replynum",replynum);
				intent.putExtra("title",title);
				intent.putExtra("content",content);
				context.startActivity(intent);
			}
		});
		
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		addView(listView, params);
		System.out.println("进入函数aaa");
		Runnable run = new myThread();
		new Thread(run).start();
		
	}
	
	private class myThread implements Runnable {
		@Override
		public void run() {
			System.out.println("myName--->"+myName);
			GetJsonArray();
			Message message = new Message();
			System.out.println("进入函数");
			circleList = new ActionUtils().FetchJoinCircle(URL_CIRCLELIST, uid);
			message.what = OK;
			myHandler.sendMessage(message);
		}
	}

	class ListAdapter extends BaseAdapter {
		
		int count = 10;

		@Override
		public int getCount() {
			return count;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			System.out.println("begin to get--->");
			//LayoutInflater inflater = LayoutInflater.from(getContext());
			//View view = inflater.inflate(R.layout.listview_item_hot, null);
			LayoutInflater inflater = LayoutInflater.from(getContext());
			View view = inflater.inflate(R.layout.circle_item_hot, null);
			
			LinearLayout aa = (LinearLayout)view.findViewById(R.id.main_linear_layout);
			//for(int i=0;i<discusslist.size();i++)
			//{
				
				HashMap<String,String> map=discusslist.get(position);
				System.out.println("title-->"+map.get("title")+"content--->"+map.get("content"));
				//TextView tv = (TextView) view
				//		.findViewById(R.id.txt_wb_item_content);
				TextView tv = (TextView) view
						.findViewById(R.id.content);
				tv.setText(map.get("content"));
				TextView title = (TextView) view
						.findViewById(R.id.sender);
				title.setText(map.get("title"));
				TextView time = (TextView) view
						.findViewById(R.id.send_time);
				time.setText(map.get("time"));
				TextView state = (TextView) view
						.findViewById(R.id.state);
				state.setText(map.get("replynum"));
			//}
			/*
			TextView tv = (TextView) view
					.findViewById(R.id.txt_wb_item_content);
			tv.setText(circleList.get(position).getDescription());
			LinearLayout subpost = (LinearLayout) view.findViewById(R.id.subpost);
			//subpost.setVisibility(View.GONE);
			subpost=(LinearLayout) view.findViewById(R.id.down);
			//subpost.setVisibility(View.GONE);
			ImageView img = (ImageView) view.findViewById(R.id.img_wb_item_content_pic);
			//img.setVisibility(View.GONE);
			//subpost.setVisibility(View.GONE);
			tv = (TextView) view.findViewById(R.id.txt_wb_item_time);
			tv.setText("");
			tv = (TextView) view.findViewById(R.id.txt_wb_item_redirect);
			tv.setText("" + circleList.get(position).getCircleId());
			tv = (TextView) view.findViewById(R.id.txt_wb_item_uname);
			tv.setText("" + circleList.get(position).getCircleName());
			*/
			return view;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		this.visibleItemCount = visibleItemCount;
		lastItem = firstVisibleItem + visibleItemCount - 1;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		this.scrollState = scrollState;
	}
	

	private JSONArray GetJsonArray()
    {
		System.out.println("aaaaa--->");
    	HttpClient client=new DefaultHttpClient();
    	StringBuilder builder=new StringBuilder();
    	JSONArray jsonarray=null;
    	HttpPost post=new HttpPost("http://rebook.sinaapp.com/discuss.php");
    	List<NameValuePair> parameter=new ArrayList<NameValuePair>(); 
    	//parameter.add(new BasicNameValuePair("page",String.valueOf(page)));
    	parameter.add(new BasicNameValuePair("cid",String.valueOf(cid)));
    	parameter.add(new BasicNameValuePair("username",String.valueOf(myName)));
    	try {
    		post.setEntity(new UrlEncodedFormEntity(parameter,HTTP.UTF_8));
			HttpResponse response=client.execute(post);
			BufferedReader reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			for(String s=reader.readLine();s!=null;s=reader.readLine())
			{
				builder.append(s);
			}
			if(builder.toString().equals("end"))
			{
				System.out.println("th end");
				//page=page-1;
			}
			else
			{
				System.out.println("builder--->"+builder.toString());
				jsonarray=new JSONArray(builder.toString());
				JSONObject jsonObject;
				discusslist.clear();
				for(int i=0;i<jsonarray.length();i++)
				{
					jsonObject=jsonarray.getJSONObject(i);
					HashMap<String,String> map=new HashMap<String,String>();
					if(jsonObject.getString("title").length()>10)
					{
						StringBuffer smalltitle=new StringBuffer(jsonObject.getString("title").substring(0,9));
						smalltitle.append("……");
						map.put("smalltitle",smalltitle.toString());
					}
					else
					{
						map.put("smalltitle",jsonObject.getString("title"));
					}
					
					if(jsonObject.getString("username").length()>7)
					{
						StringBuffer smallname=new StringBuffer(jsonObject.getString("username").substring(0,7));
						smallname.append("……");
						map.put("smallusername",smallname.toString());
					}
					else
					{
						map.put("smallusername",jsonObject.getString("username"));
					}
					map.put("title",jsonObject.getString("title"));
					map.put("username",jsonObject.getString("username"));
					map.put("time",jsonObject.getString("time"));
					map.put("replynum",jsonObject.getString("replynum"));
					map.put("postid",jsonObject.getString("postid"));
					map.put("content",jsonObject.getString("content"));
					discusslist.add(map);
				}
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			System.out.println("client---->"+e.toString());
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("IO---->"+e.toString());
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			System.out.println("json---->"+e.toString());
			e.printStackTrace();
		}
    	System.out.println("size--->"+discusslist.size());
		return jsonarray;
    }
}
